/**
 * 
 */
package com.baijia.tianxiao.route.domain.channel;

import java.net.URI;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ServerHandshake;

import com.alibaba.fastjson.JSON;
import com.baijia.tianxiao.connect.common.util.ConnectUtil;
import com.baijia.tianxiao.connect.common.util.InnerAuthToken;
import com.baijia.tianxiao.connect.route.api.model.DefaultCCMessage;

/**
 * @author leiruiqi
 *
 */
public class DefaultWebSocketClient extends WebSocketClient {

	int status = 0;
	
	public DefaultWebSocketClient( URI serverUri , Draft draft ) {  
        super( serverUri, draft );  
	}  

	public DefaultWebSocketClient( URI serverURI ) {  
        super( serverURI );  
	}  


	@Override  
    public void onOpen( ServerHandshake handshakedata ) { 
		status = 1;
            System.out.println( "opened connection" );  
            // if you plan to refuse connection based on ip or httpfields overload: onWebsocketHandshakeReceivedAsClient  
    }  

    @Override  
    public void onMessage( String message ) {  
            System.out.println( "received: " + message );  
    }  

    @Override  
    public void onFragment( Framedata fragment ) {  
            System.out.println( "received fragment: " + new String( fragment.getPayloadData().array() ) );  
    }  

    @Override  
    public void onClose( int code, String reason, boolean remote ) {  
            // The codecodes are documented in class org.java_websocket.framing.CloseFrame  
    	status = -1;
            System.out.println( "Connection closed by " + ( remote ? "remote peer" : "us" ) );  
    }  

    @Override  
    public void onError( Exception ex ) {  
            ex.printStackTrace();  
            // if the error is fatal then onClose will be called additionally  
    }  

	public static void main(String[] args) throws Exception{
		//DefaultWebSocketClient client = new DefaultWebSocketClient();
		//String token = "8208a92ac6976e22b5c81484caf0cfff";
		InnerAuthToken authToken = new InnerAuthToken();
		authToken.setDomain("inner");
		authToken.setUserType("tx-cr");
		authToken.setTime(System.currentTimeMillis());
		String tokenStr = ConnectUtil.getTokenByBizName(JSON.toJSONString(authToken));
		DefaultWebSocketClient c = new DefaultWebSocketClient( new URI( "ws://tx-cc:17081/ws/tx-inner?user_token="+tokenStr ), new Draft_17() );   
        c.connectBlocking(); 
        DefaultCCMessage msg = new DefaultCCMessage();
        msg.setType("ping");
        String jsonStr = JSON.toJSONString(msg);
        c.send(jsonStr); 
	}
}
